package com.ww.springboot.dd.amazon;

import cn.hutool.core.lang.Assert;
import com.ww.springboot.boot.utils.Func;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-09-27 10:59
 */
@Slf4j
public class AmRespWrapper {

    /**
     *
     * @param contextList
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> List<T> decode(List<String> contextList,Class<T> clazz) {
        try{
            String header = contextList.get(0);
            List<String> headerList = Func.toStrList("\\t", header);
            headerList = headerList.stream().map(s->s.replace("-","")).collect(Collectors.toList());
            System.out.println(headerList);
            Field[] declaredFields = clazz.getDeclaredFields();
            Map<Integer,Field> map = new HashMap<>();
            for (Field declaredField : declaredFields) {
                int index = headerList.indexOf(declaredField.getName().toLowerCase());
                Assert.notNull(index,declaredField.getName()+ "字段不存在!");
                map.put(index,declaredField);
            }
            List<T> data = new ArrayList<>();
            for (int i = 1; i < contextList.size(); i++) {
                T t = clazz.newInstance();
                String context = contextList.get(i);
                List<String> valueList = Func.toStrList("\\t", context);
                for (int i1 = 0; i1 < valueList.size(); i1++) {
                    Field field = map.get(i1);
                    if(field == null){
                        continue;
                    }
                    field.setAccessible(true);
                    field.set(t,valueList.get(i1));
                }
                data.add(t);
            }
            return data;
        }catch (Exception e){
            log.error("AmRespWrapper 解析回执异常!",e);
            throw new RuntimeException("AmRespWrapper 解析回执异常!" + e.getMessage());
        }
    }
}
